package com.sheep.juc;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author wangze
 * @date 2020-10-22 14:09.
 **/
public class CacheDataSample<K, V> {
	private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	final Lock r = lock.readLock();
	final Lock w = lock.writeLock();
	private final Map<K, V> map = new TreeMap<>();


	public V get(K key, V v) {

		//为空，获取写锁
		r.lock();
		try {
			//判断是否为空
			if (map.get(key) == null) {
				r.unlock();
				w.lock();
				try {
					// 需要再次判断是否为空
					if (map.get(key) == null) {
						// 从数据库中读取
						map.put(key, v);
						return v;
					}

				} finally {
					w.unlock();
				}
			}

			return map.get(key);
		} finally {
			r.unlock();
		}


	}

}
